package com.ptbuy;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ptbuy.adapter.MediaPagerAdapter;
import com.ptbuy.adapter.ProductAdapter;
import com.ptbuy.callback.ExportMsgCall;
import com.ptbuy.db.dao.ClientDao;
import com.ptbuy.db.dao.ExportDao;
import com.ptbuy.db.dao.ProductDao;
import com.ptbuy.db.pojo.ClientPojo;
import com.ptbuy.db.pojo.ProductPojo;
import com.ptbuy.frebook.FrebootActivity;
import com.ptbuy.share.ShareUtils;
import com.ptbuy.signature.SingDialogAcvity;
import com.ptbuy.statanalysys.StatanAnalysisActivity;
import com.ptbuy.tranrecord.TranRecordActivity;
import com.ptbuy.update.UpdateTask;
import com.ptbuy.utils.Constants;
import com.ptbuy.utils.ExportUtils;
import com.ptbuy.utils.MineType;
import com.ptbuy.utils.MyFileUtils;
import com.ptbuy.utils.ToastUtil;
import com.ptbuy.upload.Upload;
import com.ptbuy.utils.Utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;

/**
 * 没有输入的时候显示下拉还是有问题，第一次没有提，第二次就开始有问题了
 * 2024年10月25日18:08:25 增加照片个数和视频个数记录
 */
public class MainActivity extends AppCompatActivity {

    //商品名称,价格
    EditText productPrice;
    AutoCompleteTextView productName;
    TextView totalProduct, productTotalPrice;

    ImageView mainSet;

    //清空列表,拍照录屏,确定,保存,交易记录,统计分析,导入已有数据

    //商品ListViewss
    ListView productListView;

    private ClientDao clientDao;
    private ProductDao productDao;
    private ProductAdapter productAdapter;
    private List<ProductPojo> productPojos;

    //拍照录屏的地方
    private MediaPagerAdapter adapter;
    private List<String> mediaUrls;
    private List<String> mediaUrlsView;
    private String filePath;

    //首先定义请求变量
    private static final String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.REQUEST_INSTALL_PACKAGES};
    //请求状态码，请求码的作用是与回调函数进行匹配的，这样就可以对不同权限操作进行不同的提示
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    String text = "";//分享内容


    private Upload upload;//数据上传类


    private ActivityResultLauncher<Intent> register;

    private int optType = 0;//0、拍照；1、录像；2、选择相册

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        productName = findViewById(R.id.productName);
        Constants.CurrentContext = this;
        productName.addTextChangedListener(new textCgangListener());
        upload = new Upload();
        productPrice = findViewById(R.id.productPrice);

        forces();


        totalProduct = findViewById(R.id.totalProduct);
        productTotalPrice = findViewById(R.id.productTotalPrice);
        //使用ActivityCompat.requestPermissions进行动态权限申请
        productDao = new ProductDao();
        clientDao = new ClientDao();

        //清空列表
        findViewById(R.id.clearList).setOnClickListener(v -> clearList());
        //拍照录屏
        findViewById(R.id.myCamera).setOnClickListener(v -> myCamera(0));
        //确定
        findViewById(R.id.confirm).setOnClickListener(v -> confirm());
        //保存
        findViewById(R.id.save).setOnClickListener(v -> save());
        // 交易记录
        findViewById(R.id.trade).setOnClickListener(v -> trade());
        //统计分析
        findViewById(R.id.statAnalys).setOnClickListener(v -> statAnalys());
        //导入已有数据
        findViewById(R.id.importData).setOnClickListener(v -> importData());

        productListView = findViewById(R.id.productListView);

        regist();

        initListView();//初始化列表

        mainSet = findViewById(R.id.mainSet);
        mainSet.setOnClickListener(v -> {
            PopupMenu popupMenu = new PopupMenu(this, findViewById(R.id.mainSet));
            // 使用Menu的XML资源文件来定义菜单项
            popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

            popupMenu.setOnMenuItemClickListener(item -> {
                // 处理菜单项的点击事件
                switch (item.getItemId()) {
                    case R.id.checkUpdate:
                        // 检查更新
                        new UpdateTask(UpdateTask.MANU).executeOnExecutor(Executors.newCachedThreadPool());
                        break;
                    case R.id.ptBuyShareWeChat:
                        //分享
                        text = "二手奢侈品交易助手\nhttp://" + Constants.IP + "/ptbuy/";
                        ShareUtils.shareToWeChat(text, this);
                        break;
                    case R.id.ptBuyShareQQ:
                        //分享
                        text = "二手奢侈品交易助手\nhttp://" + Constants.IP + "/ptbuy/";
                        ShareUtils.shareToQQ(text, this);
                        break;
                    case R.id.about:
                        // 关于
                        showAboutDialog();
                        break;
                    case R.id.frebook:
                        //意见反馈
                        Intent intent = new Intent(this, FrebootActivity.class);
                        startActivity(intent);
                        break;
                }
                return true;
            });

            popupMenu.show(); // 显示下拉菜单
        });

    }

    //失去焦点关闭软键盘
    private void forces() {
        productName.clearFocus();
        productPrice.clearFocus();
        InputMethodManager systemService = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        systemService.hideSoftInputFromWindow(productPrice.getWindowToken(), 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        new UpdateTask(UpdateTask.AUTO).executeOnExecutor(Executors.newCachedThreadPool());
    }

    ArrayAdapter<String> adapterText111;
    List<String> list = new ArrayList<>();

    //监听商品输入框
    private class textCgangListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // 在文本改变之前调用
            adapterText111 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, list);
            productName.setAdapter(adapterText111);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // 文本改变时调用
            String s1 = s.toString();
            if (!"".equalsIgnoreCase(s1)) {
                List<String> list1 = productDao.queryProductName(s1 + "%");
                list.clear();
                list.addAll(list1);
            } else {
                list.clear();
            }
            adapterText111.notifyDataSetChanged();

        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }

    private void showAboutDialog() {
        //显示dialog提示框
        View dialogView = LayoutInflater.from(this).
                inflate(R.layout.activity_about, null);
        TextView appVersion = dialogView.findViewById(R.id.appVersion);
        appVersion.setText("版本：v" + Utils.getVersion());
        Dialog clauseDialog = new android.app.AlertDialog.
                Builder(this).
                setView(dialogView).
                show();
        //设置点击弹出框以外不关闭
        clauseDialog.setCancelable(false);
        final Button mButton = dialogView.findViewById(R.id.clause_submit);
        //确定按钮监听
        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                clauseDialog.dismiss();
            }
        });
    }

    //初始化列表
    private void initListView() {
        productPojos = productDao.queryExportPojo(null);
        productAdapter = new ProductAdapter(this, productPojos);
        productAdapter.setProductInterface(new opt());
        productListView.setAdapter(productAdapter);
        mathTool();
    }

    private class opt implements ProductAdapter.ProductInterface {

        @Override
        public void execute(int type, ProductPojo productPojo) {
            /**
             * type 1:删除；2：查看照片；3、修改
             */
            if (type == 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("您确定删除？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        productPojos.remove(productPojo);
                        productAdapter.notifyDataSetChanged();
                        productDao.delInfo(String.valueOf(productPojo.getId()));
                        String mult = productPojo.getMult();
                        try {
                            /**
                             * 避免出现异常
                             */
                            if ("".equalsIgnoreCase(mult)) {
                                List<String> list = JSONArray.parseArray(mult, String.class);
                                for (String path : list) {
                                    Constants.deleteFile(path);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        mathTool();
                        Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_LONG).show();
                    }
                });
                builder.setNeutralButton("取消", null);
                builder.show(); //调用show()方法来展示对话框
            } else if (type == 2) {
                myCameraPreView(productPojo);
            } else {
                //修改
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_product_modify, null);
                EditText name = view.findViewById(R.id.name);
                name.setText(productPojo.getProductName());
                EditText price = view.findViewById(R.id.price);
                price.setText(productPojo.getProductPrice() + "");
                AlertDialog.Builder builder123 = new AlertDialog.Builder(MainActivity.this);
                builder123.setView(view);
                builder123.setTitle("信息修改");
                builder123.setCancelable(false);
                builder123.setPositiveButton("确定", null);
                builder123.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                AlertDialog alertDialog = builder123.create();
                alertDialog.show();
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        productDao.updateInfo(productPojo.getId() + "", name.getText().toString(), price.getText().toString());
                        ToastUtil.show(MainActivity.this, "修改成功");
                        int i = productPojos.indexOf(productPojo);
                        productPojos.remove(productPojo);
                        productPojo.setProductName(name.getText().toString());
                        try {
                            productPojo.setProductPrice(price.getText().toString());
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        productPojos.add(i, productPojo);
                        productAdapter.notifyDataSetChanged();
                        mathTool();
                    }
                });
            }
        }
    }

    //清空列表
    private void clearList() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("提示");
        builder.setMessage("您确定清空列表？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                productPojos.clear();
                productAdapter.notifyDataSetChanged();
                productDao.delInfoByStatus();
                mathTool();
                Toast.makeText(MainActivity.this, "清空完成", Toast.LENGTH_LONG).show();
            }
        });
        builder.setNeutralButton("取消", null);
        builder.show(); //调用show()方法来展示对话框
    }

    ViewPager viewPager;
    TextView mediaSum;


    /**
     * 查看和下面的myCamera拍照录屏分开吗，这样可以避免临时拍照的时候和查看照片混乱，查看了照片临时拍照里面就变成了查看的照片，所以需要分开
     *
     * @param productPojo
     */
    private void myCameraPreView(ProductPojo productPojo) {
        myPhoto = 0;
        myVideo = 0;

        /**
         * 查看这里如果是空的，那么定义，如果不是空的则清空里面内容
         */
        if (mediaUrlsView == null) {
            mediaUrlsView = new ArrayList<>();
        } else {
            mediaUrlsView.clear();
        }

        String mult = productPojo.getMult();

        List<String> list = JSONArray.parseArray(mult, String.class);

        View view1 = LayoutInflater.from(this).inflate(R.layout.activity_media_page, null);

        /**
         * 拍照
         */

        view1.findViewById(R.id.takePicture).setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("需要获取相机、媒体权限才能进行拍照，是否授权？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                700);

                    }
                });
                builder.setNeutralButton("否", null);
                builder.show(); //调用show()方法来展示对话框
            } else {
                photo(1111);
            }

        });

        /**
         * 录屏
         */
        view1.findViewById(R.id.videoRecord).setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("需要获取相机、媒体权限才能进行录像，是否授权？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                701);
                    }
                });
                builder.setNeutralButton("否", null);
                builder.show(); //调用show()方法来展示对话框
            } else {
                video(2222);
            }
        });

        /**
         * 选择相册
         */
        view1.findViewById(R.id.chosePhotoAlbum).setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("需要获取媒体权限才能完成相册选择，是否授权？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                702);
                    }
                });
                builder.setNeutralButton("否", null);
                builder.show(); //调用show()方法来展示对话框
            } else {
                photoAlbum(4567);
            }

        });

        mediaSum = view1.findViewById(R.id.mediaSum);
//        LinearLayout mediaLayout = view1.findViewById(R.id.mediaLayout);
//        mediaLayout.setVisibility(View.GONE);


        viewPager = view1.findViewById(R.id.viewPager);//录像
        if (list != null && list.size() > 0) {
            mediaUrlsView.addAll(list);
        }

        mediaSumText(mediaUrlsView);

        adapter = new MediaPagerAdapter(this, mediaUrlsView, 1);
        adapter.setOnItemDeleteListener(new deleteListener());
        viewPager.setAdapter(adapter);

        AlertDialog.Builder builder123 = new AlertDialog.Builder(this);
        builder123.setView(view1);
        builder123.setCancelable(false);
        builder123.setPositiveButton("确定", null);
        builder123.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        AlertDialog alertDialog = builder123.create();
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaUrlsView != null && mediaUrlsView.size() > 0) {
                    String mult = JSON.toJSONString(mediaUrlsView);
                    productDao.updateInfoMult(productPojo.getId() + "", mult, myPhoto, myVideo);
                    ToastUtil.show(MainActivity.this, "修改成功");
                    int i = productPojos.indexOf(productPojo);
                    productPojos.remove(productPojo);
                    productPojo.setMult(mult);
                    productPojos.add(i, productPojo);
                } else {
                    productDao.updateInfoMult(productPojo.getId() + "", "", 0, 0);
                    int i = productPojos.indexOf(productPojo);
                    productPojos.remove(productPojo);
                    productPojo.setMult("");
                    productPojos.add(i, productPojo);
                }
                productAdapter.notifyDataSetChanged();
                alertDialog.dismiss();
            }
        });

        //获取屏幕分辨率
        DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();

        int height = metrics.heightPixels;

        // 设置对话框的高度
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(alertDialog.getWindow().getAttributes());
        layoutParams.height = height / 2; // 设置所需的高度，单位为像素
        alertDialog.getWindow().setAttributes(layoutParams);
    }

    //拍照
    private void photo(int RESULT_CODE) {
        try {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                String filename = UUID.randomUUID().toString();
                File imageFile = File.createTempFile(filename, ".jpg", storageDir);
                filePath = imageFile.getPath();
                Uri uri = FileProvider.getUriForFile(this, "com.ptbuy.fileprovider", imageFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                optType = 0;
                startActivityForResult(takePictureIntent, RESULT_CODE);
//                register.launch(takePictureIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //录像
    private void video(int RESULT_CODE) {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
            try {
                File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                String filename = UUID.randomUUID().toString();
                File imageFile = File.createTempFile(filename, ".mp4", storageDir);
                filePath = imageFile.getPath();
                Uri uri = FileProvider.getUriForFile(this, "com.ptbuy.fileprovider", imageFile);
                takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                optType = 1;
                startActivityForResult(takeVideoIntent, RESULT_CODE);
//                register.launch(takeVideoIntent);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //选择相册
    private void photoAlbum(int RESULT_CODE) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");  // 任意类型的文件
        optType = 3;
        startActivityForResult(intent, RESULT_CODE);
//        register.launch(intent);
    }

    private void regist() {
        /**
         * 暂时没用
         */
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result != null) {
                    if (result.getResultCode() == RESULT_OK) {
                        if (filePath != null) {
                            File file = new File(filePath);
                            if (file.exists()) {
                                mediaUrlsView.add(filePath);
                                adapter.notifyDataSetChanged();
                                if (optType == 1) {
                                    myVideo++;
                                } else {
                                    myPhoto++;
                                }
                                mediaMath();
                            }
                        }
                    }
                }
            }
        });
    }

    //拍照录屏,type:0、拍照录屏；
    private void myCamera(int type) {

        forces();

        myPhoto = 0;
        myVideo = 0;
        View view1 = LayoutInflater.from(this).inflate(R.layout.activity_media_page, null);
        LinearLayout mediaLayout = view1.findViewById(R.id.mediaLayout);
        mediaSum = view1.findViewById(R.id.mediaSum);
        if (mediaUrls == null) {
            mediaUrls = new ArrayList<>();
        } else {
            mediaSumText(mediaUrls);
        }
        mediaLayout.setVisibility(View.VISIBLE);
        /**
         * 拍照
         */

        view1.findViewById(R.id.takePicture).setOnClickListener(v -> {

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("需要获取相机、媒体权限才能进行拍照，是否授权？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                600);

                    }
                });
                builder.setNeutralButton("否", null);
                builder.show(); //调用show()方法来展示对话框
            } else {
                photo(111);
            }
        });

        /**
         * 录屏
         */
        view1.findViewById(R.id.videoRecord).setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("需要获取相机、媒体权限才能进行录像，是否授权？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                601);
                    }
                });
                builder.setNeutralButton("否", null);
                builder.show(); //调用show()方法来展示对话框
            } else {
                video(222);
            }
        });

        /**
         * 选择相册
         */
        view1.findViewById(R.id.chosePhotoAlbum).setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("需要获取媒体权限才能完成相册选择，是否授权？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                602);
                    }
                });
                builder.setNeutralButton("否", null);
                builder.show(); //调用show()方法来展示对话框
            } else {
                photoAlbum(4561);
            }
        });


        viewPager = view1.findViewById(R.id.viewPager);//录像

        adapter = new MediaPagerAdapter(this, mediaUrls, type);
        adapter.setOnItemDeleteListener(new deleteListener());
        viewPager.setAdapter(adapter);

        AlertDialog.Builder builder123 = new AlertDialog.Builder(this);
        builder123.setView(view1);
        builder123.setCancelable(false);
        builder123.setPositiveButton("确定", null);
        builder123.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        AlertDialog alertDialog = builder123.create();
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        //获取屏幕分辨率
        DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();

        int height = metrics.heightPixels;

        // 设置对话框的高度
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(alertDialog.getWindow().getAttributes());
        layoutParams.height = height / 2; // 设置所需的高度，单位为像素
        alertDialog.getWindow().setAttributes(layoutParams);
    }

    private class deleteListener implements MediaPagerAdapter.OnItemDeleteListener {

        @Override
        public void DeleteItem(String filePath, int type) {

            Constants.deleteFile(filePath);
            if (type == 0) {
                mediaUrls.remove(filePath);
                mediaSumText(mediaUrls);
            } else {
                mediaUrlsView.remove(filePath);
                mediaSumText(mediaUrlsView);
            }
            adapter.notifyDataSetChanged();
            viewPager.setAdapter(adapter);
        }
    }

    /**
     * 显示照片照片张数的
     *
     * @param list
     */
    private void mediaSumText(List<String> list) {
        for (String media : list) {
            if (media.contains(".mp4")) {
                myVideo++;
            } else {
                myPhoto++;
            }
        }

        mediaSum.setText("照片" + myPhoto + "张；视频" + myVideo + "个");
    }

    //确定
    private void confirm() {
        forces();
        String productNameText = productName.getText().toString();
        String productPriceText = productPrice.getText().toString();
        if ("".equalsIgnoreCase(productPriceText)) {
            Toast.makeText(this, "价格不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equalsIgnoreCase(productNameText)) {
            Toast.makeText(this, "名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String mult = "";
        if (mediaUrls != null && mediaUrls.size() > 0) {
            mult = JSON.toJSONString(mediaUrls);
        }
        Date date = new Date();
        String currentTime = Utils.getCurrentTime(date);
        productDao.addInfo(productNameText, productPriceText, mult, null, currentTime, myPhoto, myVideo);
        List<ProductPojo> myProductPojos = productDao.queryExportPojo(null);
        productPojos.clear();
        productPojos.addAll(myProductPojos);
        productAdapter.notifyDataSetChanged();
        mathTool();
        productName.setText("");
        productPrice.setText("");
        if (mediaUrls != null) {
            mediaUrls.clear();
        }
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    ImageView singatureImg;
    String singaturePath;

    //保存
    private void save() {
        forces();
        int size = productPojos.size();
        if (size == 0) {
            ToastUtil.show(this, "没有添加商品");
            return;
        }
        singaturePath = null;
        //修改
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_save, null);
        EditText coumName = view.findViewById(R.id.coumName);//客户姓名
        Button singatureBtn = view.findViewById(R.id.singatureBtn);//客户签名按钮

        singatureBtn.setOnClickListener(v -> {
            Intent intent = new Intent(this, SingDialogAcvity.class);
            startActivityForResult(intent, 888);
        });

        singatureImg = view.findViewById(R.id.singatureImg);//客户签名照片
        singatureImg.setVisibility(View.GONE);
        EditText coumPhone = view.findViewById(R.id.coumPhone);//客户电话
        EditText agent = view.findViewById(R.id.agent);//收购人
        AlertDialog.Builder builder123 = new AlertDialog.Builder(MainActivity.this);
        builder123.setView(view);
        builder123.setTitle("交易信息填写");
        builder123.setCancelable(false);
        builder123.setPositiveButton("确定", null);
        builder123.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        AlertDialog alertDialog = builder123.create();
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                String coumNameText = coumName.getText().toString();
                String coumPhoneText = coumPhone.getText().toString();
                String agentText = agent.getText().toString();
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String s = totalProduct.getText().toString();
                String s1 = productTotalPrice.getText().toString();
                String replace = s1.replace(",", "");
                String dealPrice = Utils.getNumlStr(replace);


                clientDao.addInfo(uuid, coumNameText, agentText, s, dealPrice, coumPhoneText, singaturePath);
                productDao.updateStatusInfo(uuid);
                ToastUtil.show(MainActivity.this, "保存成功");
                productPojos.clear();
                productAdapter.notifyDataSetChanged();
                mathTool();

                //导出提示
                exportPdfTip(uuid, s, s1);

                /**
                 * 上传数据
                 */

                ClientPojo clientPojo = clientDao.queryClientInfo(uuid);

                upload.addClientInfo(clientPojo);

                List<ProductPojo> pojoList = productDao.queryExportPojo(uuid);
                upload.addProdoctInfo(pojoList);
            }
        });
    }

    List<ProductPojo> exportPojoList;
    String exportTotalProduct;
    String exportProductTotalPrice;


    private AlertDialog exportShow;

    private void exportPdfTip(String pid, String totalProduct, String productTotalPrice) {
        exportTotalProduct = totalProduct;
        exportProductTotalPrice = productTotalPrice;
        exportPojoList = productDao.queryInfo(0, 0, " and pid ='" + pid + "'");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage("是否导出签字确认单？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Message obtainMessage = mHandler.obtainMessage();
                obtainMessage.what = 6;
                mHandler.sendMessage(obtainMessage);
            }
        });
        builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        exportShow = builder.show();
        exportShow.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            Message obtainMessage = mHandler.obtainMessage();
            obtainMessage.what = 6;
            mHandler.sendMessage(obtainMessage);
        });

        //调用show()方法来展示对话框
    }

    ExportDao exportDao;

    // 交易记录
    private void trade() {
        Intent intent = new Intent(this, TranRecordActivity.class);
        startActivity(intent);
        finish();
    }

    //统计分析
    private void statAnalys() {
        Intent intent = new Intent(this, StatanAnalysisActivity.class);
        startActivity(intent);
        finish();
    }

    TextView choseFilePath;

    //导入已有数据
    private void importData() {
        if (!Utils.hasAllFilesAccess()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("提示");
            builder.setMessage("导入已有数据需要打开文件所有权限，是否授权？");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    Uri uri = Uri.fromParts("package", Constants.CurrentContext.getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                }
            });
            builder.setNeutralButton("否", null);
            builder.show(); //调用show()方法来展示对话框
        } else {
            View importView = LayoutInflater.from(this).inflate(R.layout.import_data, null);
            Button choseFile = importView.findViewById(R.id.choseFile);//选择文件按钮
            Button importExDownload = importView.findViewById(R.id.importExDownload);//选择文件按钮
            Button openImportExFile = importView.findViewById(R.id.openImportExFile);//打开文件
            choseFilePath = importView.findViewById(R.id.filePath);//已导入文件路径框
            TextView downFilePath = importView.findViewById(R.id.downFilePath);//已导入文件路径框
            String s = Constants.getDocument() + "import_ex.xlsx";
            downFilePath.setText(s);

            openImportExFile.setOnClickListener(v -> {
                File file = new File(Constants.getDocument() + "import_ex.xlsx");
                if (file.exists()) {
                    MineType.openFile(MainActivity.this, file);
                } else {
                    ToastUtil.show(MainActivity.this, "文件不存在");
                }
            });

            importExDownload.setOnClickListener(v -> {
                boolean b = importExDownload();
                if (b) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("下载成功：" + Constants.getDocument() + "/import_ex.xlsx；是否打开文件");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            File file = new File(Constants.getDocument() + "/import_ex.xlsx");
                            if (file.exists()) {
                                MineType.openFile(MainActivity.this, file);
                            } else {
                                ToastUtil.show(MainActivity.this, "文件丢失");
                            }
                        }
                    });
                    builder.setNeutralButton("取消", null);
                    builder.show(); //调用show()方法来展示对话框
                } else {
                    ToastUtil.show(this, "下载失败");
                }
            });
            choseFile.setOnClickListener(v -> {
                //点击选择文件,请求权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, 10);
                } else {
                    choseDocument();
                }
            });

            AlertDialog.Builder builder123 = new AlertDialog.Builder(this);
            builder123.setView(importView);
            builder123.setCancelable(false);
            builder123.setPositiveButton("确定", null);
            builder123.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog alertDialog = builder123.create();

            alertDialog.show();

            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    Message obtainMessage = mHandler.obtainMessage();
                    obtainMessage.what = 1;
                    mHandler.sendMessage(obtainMessage);

                }
            });
        }
    }

    private boolean importExDownload() {
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在下载");
        progressDialog.setCancelable(false);
        progressDialog.show();
        try {
            File file = new File(Constants.getDocument() + "import_ex.xlsx");
            InputStream inputStream = getAssets().open("import_ex.xlsx");
            String originMd5 = Utils.getFileMD5(inputStream);
            boolean isNeedCopy = false;
            if (!file.exists()) {
                isNeedCopy = true;
            } else {
                FileInputStream fileInputStream = new FileInputStream(file);
                String md5 = Utils.getFileMD5(fileInputStream);
                if (!md5.equals(originMd5))
                    isNeedCopy = true;
            }
            if (isNeedCopy) {
                inputStream = getAssets().open("import_ex.xlsx");
                OutputStream outputStream = new FileOutputStream(file.getAbsolutePath());
                byte[] buffer = new byte[1024];
                int length = 0;
                while ((length = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            progressDialog.dismiss();
        }
    }

    //选择文件方法
    private void choseDocument() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");  // 任意类型的文件
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);  //不允许多选
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 456);
    }


    /**
     * 处理导入的数据
     */
    private void importDataDeal() {
        String myFilePath = choseFilePath.getText().toString();
        File file = new File(myFilePath);
        if (!file.exists()) {
            ToastUtil.show(this, "文件不存在");
            return;
        }
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在处理数据");
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread(() -> {
            try {
                //使用的是 XML 解析功能，可以考虑如下调整（禁用某些特性）：
                System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");

                // 然后初始化 POI 相关代码
                // 打开Excel文件
                FileInputStream inputStream = new FileInputStream(file);
                Workbook workbook = new XSSFWorkbook(inputStream);

                // 获取第一个工作表
                Sheet sheet = workbook.getSheetAt(0);

                List<ProductPojo> pojoList = new ArrayList<>();

                // 遍历行
                for (Row row : sheet) {
                    int rowNum = row.getRowNum();
                    if (rowNum == 0) {
                        continue;
                    }
                    ProductPojo productPojo = new ProductPojo();
                    // 遍历单元格
                    for (Cell cell : row) {
                        int columnIndex = cell.getColumnIndex(); // 获取列索引
                        String cellValue = getCellValueAsString(cell); // 获取单元格值
                        if (columnIndex == 1) {
                            productPojo.setProductName(cellValue);
                        } else if (columnIndex == 2) {
                            if (!"".equalsIgnoreCase(cellValue)) {
                                productPojo.setProductPrice(cellValue);
                            } else {
                                productPojo.setProductPrice("0");
                            }

                        }
                    }
                    String productName = productPojo.getProductName();
                    if (productName != null && !"".equalsIgnoreCase(productName)) {
                        pojoList.add(productPojo);
                    }
                }
                // 关闭Excel文件
                workbook.close();
                inputStream.close();
                Date date = new Date();
                String currentTime = Utils.getCurrentTime(date);
                for (ProductPojo pp : pojoList) {
                    productDao.addInfo(pp.getProductName(), pp.getProductPrice() + "", "", pp.getProductPrice() + "", currentTime, 0, 0);
                }

                Message obtainMessage = mHandler.obtainMessage();
                obtainMessage.what = 3;
                mHandler.sendMessage(obtainMessage);

            } catch (Exception e) {
                e.printStackTrace();
                Message obtainMessage = mHandler.obtainMessage();
                obtainMessage.what = 2;
                mHandler.sendMessage(obtainMessage);
            } finally {
                progressDialog.dismiss();
            }
        }).start();
    }

    private static String getCellValueAsString(Cell cell) {
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                double numericCellValue = cell.getNumericCellValue();
                long l = Long.parseLong(String.valueOf(numericCellValue).replace(",", ""));
                String valueAsString = String.valueOf(l);
                return valueAsString;
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
            default:
                return "";
        }
    }


    //计算总件数和总价
    @SuppressLint("SetTextI18n")
    private void mathTool() {
        totalProduct.setText(productPojos.size() + "");
        Long sumPrice = 0L;
        for (ProductPojo pp : productPojos) {
            sumPrice += Long.parseLong(pp.getProductPrice().replace(",", ""));
        }

        DecimalFormat df1 = new DecimalFormat("#,###");
        String format1 = df1.format(sumPrice);
        productTotalPrice.setText(format1);
    }

    private void exportSuccess() {
        exportShow.dismiss();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("导出成功");
        builder.setMessage("存放位置：" + filePath);
        builder.setPositiveButton("打开文件", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                File file = new File(filePath);
                if (file.exists()) {
                    MineType.openFile(MainActivity.this, file);
                } else {
                    ToastUtil.show(MainActivity.this, "文件丢失");
                }
            }
        });
        builder.setNeutralButton("关闭", null);
        builder.show(); //调用show()方法来展示对话框
    }

    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    importDataDeal();
                    break;
                case 2:
                    ToastUtil.show(MainActivity.this, "文件处理失败");
                    break;
                case 3:
                    List<ProductPojo> myProductPojos = productDao.queryExportPojo(null);
                    productPojos.addAll(myProductPojos);
                    productAdapter.notifyDataSetChanged();
                    mathTool();
                    break;
                case 4:
                    exportSuccess();
                    break;
                case 5:
                    ToastUtil.show(MainActivity.this, "导出异常");
                    break;
                case 6:

                    if (!Utils.hasAllFilesAccess()) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("提示");
                        builder.setMessage("没有写入文件的权限，需要打开文件所有权限才能导出成功，是否授权？");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                                Uri uri = Uri.fromParts("package", Constants.CurrentContext.getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        });
                        builder.setNeutralButton("否", null);
                        builder.show(); //调用show()方法来展示对话框
                    } else {
                        ExportUtils.exportPDF(exportPojoList, singaturePath, MainActivity.this, exportTotalProduct, exportProductTotalPrice, new ExportMsgCall() {
                            @Override
                            public void exportFile(String backFilePath) {
                                if (backFilePath == null) {
                                    Message obtainMessage = mHandler.obtainMessage();
                                    obtainMessage.what = 5;
                                    mHandler.sendMessage(obtainMessage);
                                } else {
                                    filePath = backFilePath;
                                    if (exportDao == null) {
                                        exportDao = new ExportDao();
                                    }
                                    Message obtainMessage = mHandler.obtainMessage();
                                    obtainMessage.what = 4;
                                    mHandler.sendMessage(obtainMessage);
                                }
                            }
                        });
                    }
//                    exportPDF(exportPojoList, exportTotalProduct, exportProductTotalPrice);
                    break;
            }
        }
    };

    //然后Activity会有一个回调函数，可以在这个回调函数做一些提示
    //如下重写onRequestPermissionsResult方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //申请文件读写权限
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            }
        } else if (requestCode == 10) {
            choseDocument();
        } else if (requestCode == 600) {
            photo(111);
        } else if (requestCode == 601) {
            video(222);
        } else if (requestCode == 602) {
            photoAlbum(4561);
        } else if (requestCode == 700) {
            photo(1111);
        } else if (requestCode == 701) {
            video(2222);
        } else if (requestCode == 702) {
            photoAlbum(4567);
        }
    }

    //计算照片视频个数
    int myPhoto = 0;
    int myVideo = 0;

    private void mediaMath() {
        mediaSum.setText("照片" + myPhoto + "张；视频" + myVideo + "个");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 111 && resultCode == RESULT_OK) {
            // 拍照成功后的处理
            // 可以在这里获取录像的Uri等信息
            if (filePath != null) {
                File file = new File(filePath);
                if (file.exists()) {
                    mediaUrls.add(filePath);
                    adapter.notifyDataSetChanged();
                    myPhoto++;
                    mediaMath();
                }
            }
        } else if (requestCode == 222 && resultCode == RESULT_OK) {
            // 录像成功后的处理
            // 可以在这里获取录像的Uri等信息
            if (filePath != null) {
                File file = new File(filePath);
                if (file.exists()) {
                    mediaUrls.add(filePath);
                    adapter.notifyDataSetChanged();
                    myVideo++;
                    mediaMath();
                }
            }
        } else if (requestCode == 4561 && resultCode == RESULT_OK && data != null) {
            // 录像成功后的处理
            // 可以在这里获取录像的Uri等信息
            Uri uri = data.getData();
            if (uri != null) {
                // 获取图片的真实路径
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String filePath = cursor.getString(columnIndex);
                    cursor.close();
                    // 处理选中的文件uri
                    File file = new File(filePath);
                    if (file.exists()) {
                        mediaUrls.add(filePath);
                        adapter.notifyDataSetChanged();
                        myPhoto++;
                        mediaMath();
                    }
                    // 使用图片路径的代码
                    // 例如显示图片到ImageView
                    // imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

                    // 或者处理图片路径
                    // processImagePath(picturePath);
                }
            }


        } else if (requestCode == 1111 && resultCode == RESULT_OK) {
            // 拍照成功后的处理
            // 可以在这里获取录像的Uri等信息
            if (filePath != null) {
                File file = new File(filePath);
                if (file.exists()) {
                    mediaUrlsView.add(filePath);
                    adapter.notifyDataSetChanged();
                    myPhoto++;
                    mediaMath();
                }
            }
        } else if (requestCode == 2222 && resultCode == RESULT_OK) {
            // 录像成功后的处理
            // 可以在这里获取录像的Uri等信息
            if (filePath != null) {
                File file = new File(filePath);
                if (file.exists()) {
                    mediaUrlsView.add(filePath);
                    adapter.notifyDataSetChanged();
                    myVideo++;
                    mediaMath();
                }
            }
        } else if (requestCode == 4567 && resultCode == RESULT_OK && data != null) {

            Uri uri = data.getData();
            if (uri != null) {
                // 获取图片的真实路径
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String filePath = cursor.getString(columnIndex);
                    cursor.close();
                    // 录像成功后的处理
                    // 可以在这里获取录像的Uri等信息
                    File file = new File(filePath);
                    if (file.exists()) {
                        mediaUrlsView.add(filePath);
                        adapter.notifyDataSetChanged();
                        myPhoto++;
                        mediaMath();
                    }
                    // 使用图片路径的代码
                    // 例如显示图片到ImageView
                    // imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

                    // 或者处理图片路径
                    // processImagePath(picturePath);
                }
            }


        } else if (requestCode == 456 && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                // 处理选中的文件uri
                String filePath = MyFileUtils.getPathFromUri(this, uri);
                choseFilePath.setText(filePath);
            }
        } else if (requestCode == 111 || requestCode == 222) {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
        } else if (requestCode == 1111 || requestCode == 2222) {
            try {
                if (filePath != null) {
                    File file = new File(filePath);
                    if (file.exists()) {
                        file.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (requestCode == 888 && resultCode == RESULT_OK && data != null) {
            singaturePath = data.getExtras().getString("path");
            Bitmap bitmap = BitmapFactory.decodeFile(singaturePath);
            singatureImg.setImageBitmap(bitmap);
            singatureImg.setVisibility(View.VISIBLE);
        }
    }
}